/*******************************************************************************
 *  Copyright (c) 2010 Chase Technology Ltd.
 *  
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU General Public License v3.0
 *  which is available at http://www.gnu.org/licenses/
 * 
 * Contributors:
 *     Doug Satchwell - initial API and implementation
 *******************************************************************************/
package org.jfunction.ui.internal.editor;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.jfunction.ui.model.UIScenario;
import org.jfunction.ui.model.UIStep;

public class ScenarioPage extends FormPage {

	public ScenarioPage(FormEditor editor, String id, String title) {
		super(editor, id, title);
	}
	
	private UIScenario getScenario() {
		JFunctionEditor editor = (JFunctionEditor)getEditor();
		return editor.getScenario();
	}
	
	@Override
	protected void createFormContent(IManagedForm managedForm) {
		final ScrolledForm form = managedForm.getForm();
		FormToolkit toolkit = managedForm.getToolkit();
		toolkit.decorateFormHeading(form.getForm());

		Composite body = form.getBody();
		body.setLayout(new GridLayout());
		body.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
		
		Section descSection = toolkit.createSection(body, SWT.NONE);
		descSection.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,false));
		descSection.setText("Description");
		
		Text title = toolkit.createText(descSection, "hello world", SWT.WRAP | SWT.V_SCROLL);
		GridData gd = new GridData(SWT.FILL,SWT.FILL,true,true);
		gd.heightHint = 100;
		title.setLayoutData(gd);
		descSection.setClient(title);
		
		Section textSection = toolkit.createSection(body, SWT.NONE);
		textSection.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
		textSection.setText("Steps");
		
//		TextViewer viewer = new TextViewer(textSection, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
//		viewer.getTextWidget().setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
//		viewer.getTextWidget().setFont(form.getBody().getFont());
//		textSection.setClient(viewer.getTextWidget());
		
//		Document doc = new Document();
//		doc.set("hello world");
//		viewer.setDocument(doc);
//		viewer.setEditable(true);
		
		Composite textComp = toolkit.createComposite(textSection);
		GridLayout gl = new GridLayout(2,false);
		gl.marginWidth = 0;
		textComp.setLayout(gl);
		textSection.setClient(textComp);
		
		final Table stepsTable = toolkit.createTable(textComp, SWT.BORDER | SWT.NO_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
		stepsTable.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
		stepsTable.setLinesVisible(false);
		stepsTable.setHeaderVisible(true);
		final TableColumn beanTc = new TableColumn(stepsTable, SWT.NONE );
		beanTc.setText("Class");
		beanTc.setWidth(100);
		final TableColumn tc = new TableColumn(stepsTable, SWT.NONE );
		tc.setText("Text");
		tc.setWidth(100);
		ControlListener cl = new ControlListener() {
			
			@Override
			public void controlResized(ControlEvent arg0) {
				int width = stepsTable.getBounds().width - beanTc.getWidth();
				tc.setWidth(width);
			}
			
			@Override
			public void controlMoved(ControlEvent arg0) {
			}
		};		
		beanTc.addControlListener(cl);
		stepsTable.addControlListener(cl);
		
		Composite buttonComp = toolkit.createComposite(textComp);
		gd = new GridData();
		gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
		buttonComp.setLayoutData(gd);
		gl = new GridLayout();
		gl.marginWidth = 0;
		buttonComp.setLayout(gl);
		
		Button addButton = toolkit.createButton(buttonComp, "Add", SWT.PUSH);
		gd = new GridData();
		gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
		addButton.setLayoutData(gd);
		addButton.addSelectionListener(new SelectionListener() {
			
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				AddStepDialog dialog = new AddStepDialog(ScenarioPage.this.getEditorSite().getShell());
				if (dialog.open() == Window.OK) {
					
				}
			}
			
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
			}
		});
		
		Button searchButton = toolkit.createButton(buttonComp, "Search", SWT.PUSH);
		gd = new GridData();
		gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
		searchButton.setLayoutData(gd);
		searchButton.addSelectionListener(new SelectionListener() {
			
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				SearchStepDialog dialog = new SearchStepDialog(ScenarioPage.this.getEditorSite().getShell());
				if (dialog.open() == Window.OK) {
					
				}
			}
			
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
			}
		});
		
		final Button removeButton = toolkit.createButton(buttonComp, "Remove", SWT.PUSH);
		gd = new GridData();
		gd.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
		removeButton.setLayoutData(gd);
		
		TableViewer tv = new TableViewer(stepsTable);
		CellEditor classEditor = new TextCellEditor(stepsTable);
		CellEditor textEditor = new TextCellEditor(stepsTable);
		tv.setCellEditors(new CellEditor[]{classEditor,textEditor});
		tv.setColumnProperties(new String[]{"class","text"});
		tv.setCellModifier(new StepCellModifier(tv));
		tv.setContentProvider(new IStructuredContentProvider() {
			
			private UIScenario scenario;

			@Override
			public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
				this.scenario = (UIScenario)arg2;
			}
			
			@Override
			public void dispose() {
			}
			
			@Override
			public Object[] getElements(Object arg0) {
				return scenario.getSteps().toArray();
			}
		});
		tv.setLabelProvider(new ITableLabelProvider() {
			
			@Override
			public void removeListener(ILabelProviderListener arg0) {
			}
			
			@Override
			public boolean isLabelProperty(Object arg0, String arg1) {
				return true;
			}
			
			@Override
			public void dispose() {
			}
			
			@Override
			public void addListener(ILabelProviderListener arg0) {
			}
			
			@Override
			public String getColumnText(Object arg0, int arg1) {
				UIStep sb = (UIStep)arg0;
				switch(arg1) {
				case 0:
					String value = "";
					String className = sb.getClassName();
					String packageName = sb.getPackageName();
					if (className != null) {
						value = className;
						if (packageName != null) {
							value += " ("+packageName+")";
						} else {
							value += " (default package)";
						}
					}
					return value;
				case 1:
					return sb.getText();
				}
				return "?";
			}
			
			@Override
			public Image getColumnImage(Object arg0, int arg1) {
				return null;
			}
		});
		tv.addSelectionChangedListener(new ISelectionChangedListener() {
			
			@Override
			public void selectionChanged(SelectionChangedEvent arg0) {
				removeButton.setEnabled(!arg0.getSelection().isEmpty());
			}
		});
		tv.setInput(getScenario());

		form.setText("Scenario");
	}
	
	private class StepCellModifier implements ICellModifier {

		private TableViewer tv;

		public StepCellModifier(TableViewer tv) {
			this.tv = tv;
		}

		public boolean canModify(Object element, String property) {
			return true;
		}

		public Object getValue(Object element, String property) {
			UIStep sb = (UIStep)element;
			if ("class".equals(property)) {
				String name;
				if (sb.getPackageName() != null) {
					name = sb.getPackageName()+"."+sb.getClassName();
				} else {
					name = sb.getClassName();
				}
				return name;
			} else if ("text".equals(property)) {
				return sb.getText();
			}
			return "";
		}

		public void modify(Object element, String property, Object value) {
			if (element instanceof TableItem) {
				Object data = ((TableItem) element).getData();
				UIStep sb = (UIStep)data;
				if ("class".equals(property)) {
					String fullname = (String)value;
					int index = fullname.lastIndexOf('.');
					if (index == -1) {
						sb.setPackageName(null);
						sb.setClassName(fullname);
					} else {
						sb.setPackageName(fullname.substring(0,index));
						sb.setClassName(fullname.substring(index+1));
					}
				} else if ("text".equals(property)) {
					String text = (String)value;
					sb.setText(text);
				}
				tv.update(data, new String[]{property});
			}
		}
	}

}
